package com.lekang.le.service.impl;

import com.alibaba.fastjson.JSON;
import com.lekang.common.core.domain.entity.SysUser;
import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.le.domain.*;
import com.lekang.le.mapper.*;
import com.lekang.system.service.ISysUserService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AdmissionProcessServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(AdmissionProcessServiceImpl.class);

    // 流程定义常量
    private static final String PROCESS_DEFINITION_KEY = "ruzhu";
    private static final String APPLY_TASK_KEY = "applyTask";
    private static final String ASSESS_TASK_KEY = "assessTask";
    private static final String APPROVE_TASK_KEY = "approveTask";
    private static final String CONFIG_TASK_KEY = "configTask";

    // 角色常量
    private static final String RECEPTIONIST_ROLE = "jiedaiyuan";
    private static final String ASSESSOR_ROLE = "pingguyuan";
    private static final String APPROVER_ROLE = "shenpiyuan";
    private static final String CONFIGURATOR_ROLE = "peizhiyuan";
    private static final String SIGNER_ROLE = "qianyueyuan";

    // 业务类型常量
    private static final Long ADMISSION_TYPE = 3L;
    private static final Long PENDING_STATUS = 1L;
    private static final Long APPROVED_STATUS = 1L;
    private static final Long REJECTED_STATUS = 2L;

    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private PendingTasksMapper pendingTasksMapper;
    
    @Autowired
    private AccraditationRecordMapper accraditationRecordMapper;
    
    @Autowired
    private ElderlySzhMapper elderlyMapper;
    
    @Autowired
    private ISysUserService sysUserService;
    
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    
    @Autowired
    private AbilityAssessmentMapper abilityAssessmentMapper;
    
    @Autowired
    private AssessmentReportMapper assessmentReportMapper;

    /**
     * 启动入住申请流程（完整步骤）
     */
    public int startAdmissionProcess(Map<String, Object> admissionData) {
        logger.info("开始处理入住申请流程，数据: {}", admissionData);

        try {
            // 验证输入数据
            validateAdmissionData(admissionData);

            // 获取老人信息
            Map<String, Object> elderInfo = extractElderInfo(admissionData);
            System.out.println(elderInfo);            // 检查是否已存在该老人的入住申请
            validateElderlyNotExists(elderInfo);

            // 获取当前用户信息
            SysUser currentUser = getCurrentUser();

            // 保存老人基本信息
            Long elderlyId = saveElderlyInfo(elderInfo, currentUser);

            // 保存家属信息
            saveFamilyMembers(admissionData, elderlyId, currentUser);

            // 启动流程并完成申请步骤
            startProcessAndCompleteApply(elderlyId, currentUser);

            logger.info("入住申请流程启动成功，老人ID: {}", elderlyId);
            return 1;

        } catch (Exception e) {
            logger.error("启动入住申请流程失败", e);
            throw new RuntimeException("启动入住申请流程失败: " + e.getMessage());
        }
    }

    /**
     * 验证入住申请数据
     */
    private void validateAdmissionData(Map<String, Object> admissionData) {
        if (admissionData == null || admissionData.isEmpty()) {
            throw new IllegalArgumentException("接收到的数据为空");
        }
        logger.debug("验证入住申请数据通过");
    }

    /**
     * 提取老人信息
     */
    private Map<String, Object> extractElderInfo(Map<String, Object> admissionData) {
        Map<String, Object> elderInfo = null;
        System.out.println(admissionData);
        // 方式1：直接获取elder对象
        if (admissionData.get("elder") != null) {
            if (admissionData.get("elder") instanceof Map) {
                elderInfo = (Map<String, Object>) admissionData.get("elder");
            } else {
                throw new IllegalArgumentException("elder字段类型不正确，期望Map类型");
            }
        }
        // 方式2：如果elder不存在，尝试从其他字段获取
        else if (admissionData.get("name") != null) {
            elderInfo = admissionData;
        }
        // 方式3：检查是否有其他可能的字段名
        else if (admissionData.get("elderInfo") != null) {
            elderInfo = (Map<String, Object>) admissionData.get("elderInfo");
        }

        if (elderInfo == null || elderInfo.isEmpty()) {
            logger.error("可用的字段: {}", admissionData.keySet());
            throw new IllegalArgumentException("无法找到老人信息，请检查数据格式");
        }

        // 验证身份证号
        String idCard = (String) elderInfo.get("idCard");
        if (!StringUtils.hasText(idCard)) {
            throw new IllegalArgumentException("身份证号不能为空");
        }

        logger.debug("成功提取老人信息，身份证号: {}", idCard);
        return elderInfo;
    }

    /**
     * 验证老人信息不存在
     */
    private void validateElderlyNotExists(Map<String, Object> elderInfo) {
        String idCard = (String) elderInfo.get("idCard");
        ElderlySzh elderlySzh = new ElderlySzh();
        elderlySzh.setIdCard(idCard);
        List<ElderlySzh> existingElderly = elderlyMapper.selectElderlySzhList(elderlySzh);
        if (existingElderly != null && !existingElderly.isEmpty()) {
            throw new IllegalArgumentException("该身份证号的老人信息已存在，无法重复提交入住申请");
        }
    }

    /**
     * 获取当前用户
     */
    private SysUser getCurrentUser() {
        return SecurityUtils.getLoginUser().getUser();
    }

    /**
     * 保存老人基本信息
     */
    private Long saveElderlyInfo(Map<String, Object> elderInfo, SysUser currentUser) {
        // 验证老人基本信息
//        validateElderlyBasicInfo(elderlyInfo);
        
        ElderlySzh elderly = new ElderlySzh();
        elderly.setName((String) elderInfo.get("name"));
        elderly.setIdCard((String) elderInfo.get("idCard"));
        elderly.setGender((String) elderInfo.get("gender"));
        elderly.setBirthDate(parseDate(elderInfo.get("birthDate")));
        elderly.setAge(parseLong(elderInfo.get("age")));
        elderly.setContact((String) elderInfo.get("contact"));
        elderly.setAddress((String) elderInfo.get("address"));
        elderly.setEthnicity(parseLong(elderInfo.get("ethnicity")));
        elderly.setPoliticalStatus(parseLong(elderInfo.get("politicalStatus")));
        elderly.setReligion(parseLong(elderInfo.get("religiousBelief")));
        elderly.setMaritalStatus(parseLong(elderInfo.get("maritalStatus")));
        elderly.setEducation(parseLong(elderInfo.get("education")));
        elderly.setIncomeSource(parseLong(elderInfo.get("incomeSource")));
        elderly.setHobbies(parseLong(elderInfo.get("hobby")));
        elderly.setMedicalInsurance(parseLong(elderInfo.get("medicalInsurance")));
        elderly.setMedicalCardNo((String) elderInfo.get("medicalCardNo"));
        elderly.setIsDeleted(Long.valueOf("1")); // 未审核状态
        elderly.setCreateTime(DateUtils.getNowDate());
        elderly.setCreateBy(currentUser.getUserId().toString());
        
        int insertResult = elderlyMapper.insertElderlySzh(elderly);
        if (insertResult <= 0) {
            throw new RuntimeException("保存老人信息失败");
        }
        
        logger.info("老人信息保存成功，ID: {}", elderly.getId());
        return elderly.getId();
    }
    
    /**
     * 安全解析日期
     */
    private Date parseDate(Object dateObj) {
        if (dateObj == null) return null;
        if (dateObj instanceof Date) return (Date) dateObj;
        if (dateObj instanceof String) {
            try {
                return DateUtils.parseDate((String) dateObj);
            } catch (Exception e) {
                logger.warn("日期解析失败: {}", dateObj);
                return null;
            }
        }
        return null;
    }
    
    /**
     * 安全解析Long类型
     */
    private Long parseLong(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Long) return (Long) obj;
        if (obj instanceof Integer) return ((Integer) obj).longValue();
        if (obj instanceof String) {
            try {
                return Long.valueOf((String) obj);
            } catch (NumberFormatException e) {
                logger.warn("数字解析失败: {}", obj);
                return null;
            }
        }
        return null;
    }

    /**
     * 验证老人基本信息
     */
    private void validateElderlyBasicInfo(Map<String, Object> elderInfo) {
        String name = (String) elderInfo.get("name");
        String idCard = (String) elderInfo.get("idCard");
        String gender = (String) elderInfo.get("gender");
        String contact = (String) elderInfo.get("contact");

        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("老人姓名不能为空");
        }
        if (!StringUtils.hasText(idCard)) {
            throw new IllegalArgumentException("身份证号不能为空");
        }
        if (!isValidIdCard(idCard)) {
            throw new IllegalArgumentException("身份证号格式不正确");
        }
        if (!StringUtils.hasText(gender)) {
            throw new IllegalArgumentException("性别不能为空");
        }
        if (!StringUtils.hasText(contact)) {
            throw new IllegalArgumentException("联系电话不能为空");
        }
        if (!isValidPhone(contact)) {
            throw new IllegalArgumentException("联系电话格式不正确");
        }
    }

    /**
     * 验证身份证号格式
     */
    private boolean isValidIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return false;
        }
        // 简单的身份证号格式验证
        return idCard.matches("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");
    }

    /**
     * 验证手机号格式
     */
    private boolean isValidPhone(String phone) {
        if (phone == null) {
            return false;
        }
        // 简单的手机号格式验证
        return phone.matches("^1[3-9]\\d{9}$");
    }

    /**
     * 保存家属信息
     */
    private void saveFamilyMembers(Map<String, Object> admissionData, Long elderlyId, SysUser currentUser) {
        List<Map<String, Object>> familyMembers = (List<Map<String, Object>>) admissionData.get("familyMembers");
        if (familyMembers != null && !familyMembers.isEmpty()) {
            // 验证家属信息
            validateFamilyMembers(familyMembers);

            // 批量保存家属信息
            List<FamilyMember> familyMemberList = new ArrayList<>();
        for (Map<String, Object> member : familyMembers) {
            FamilyMember familyMember = new FamilyMember();
            familyMember.setElderlyId(elderlyId);
            familyMember.setName((String) member.get("name"));
            familyMember.setContact((String) member.get("phone"));
            familyMember.setRelationship((String) member.get("relationship"));
            familyMember.setCreateTime(DateUtils.getNowDate());
                familyMember.setCreateBy(currentUser.getUserId().toString());
                familyMemberList.add(familyMember);
            }

            // 批量插入
            for (FamilyMember familyMember : familyMemberList) {
//            familyMemberMapper.insertFamilyMember(familyMember);
        }

            logger.info("家属信息保存成功，数量: {}", familyMembers.size());
        }
    }

    /**
     * 验证家属信息
     */
    private void validateFamilyMembers(List<Map<String, Object>> familyMembers) {
        for (Map<String, Object> member : familyMembers) {
            String name = (String) member.get("name");
            String phone = (String) member.get("phone");
            String relationship = (String) member.get("relationship");

            if (!StringUtils.hasText(name)) {
                throw new IllegalArgumentException("家属姓名不能为空");
            }
            if (!StringUtils.hasText(phone)) {
                throw new IllegalArgumentException("家属联系电话不能为空");
            }
            if (!StringUtils.hasText(relationship)) {
                throw new IllegalArgumentException("家属关系不能为空");
            }
        }
    }

    /**
     * 启动流程并完成申请步骤
     */
    private void startProcessAndCompleteApply(Long elderlyId, SysUser currentUser) {
        // 获取各角色用户
        Map<String, SysUser> roleUsers = getRoleUsers();

        // 设置流程变量
        Map<String, Object> processVars = new HashMap<>();
        processVars.put("assignee1", currentUser.getUserId().toString());
        processVars.put("assignee2", roleUsers.get(ASSESSOR_ROLE).getUserId().toString());
        processVars.put("assignee3", roleUsers.get(APPROVER_ROLE).getUserId().toString());
        processVars.put("assignee4", roleUsers.get(CONFIGURATOR_ROLE).getUserId().toString());
        processVars.put("assignee5", roleUsers.get(SIGNER_ROLE).getUserId().toString());

        // 启动流程
        runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, elderlyId.toString(), processVars);

        // 完成申请任务
        completeTask(elderlyId, currentUser.getUserId().toString(), APPLY_TASK_KEY);

        // 保存审批记录
        saveApprovalRecord(elderlyId, currentUser, "申请入住", "入住评估",
                roleUsers.get(ASSESSOR_ROLE), 0L, APPROVED_STATUS);

        // 创建评估员待办任务
        createPendingTask(elderlyId, roleUsers.get(ASSESSOR_ROLE), currentUser, 1L);

        logger.info("流程启动并完成申请步骤，老人ID: {}", elderlyId);
    }

    /**
     * 获取各角色用户
     */
    private Map<String, SysUser> getRoleUsers() {
        Map<String, SysUser> roleUsers = new HashMap<>();

        SysUser assessor = sysUserService.selectUserByRoleId(ASSESSOR_ROLE);
        if (assessor == null) {
            throw new RuntimeException("未配置评估员，请联系管理员");
        }
        roleUsers.put(ASSESSOR_ROLE, assessor);
        
        SysUser approver = sysUserService.selectUserByRoleId(APPROVER_ROLE);
        if (approver == null) {
            throw new RuntimeException("未配置审批员，请联系管理员");
        }
        roleUsers.put(APPROVER_ROLE, approver);
        
        SysUser configurator = sysUserService.selectUserByRoleId(CONFIGURATOR_ROLE);
        if (configurator == null) {
            throw new RuntimeException("未配置配置员，请联系管理员");
        }
        roleUsers.put(CONFIGURATOR_ROLE, configurator);
        
        SysUser signer = sysUserService.selectUserByRoleId(SIGNER_ROLE);
        if (signer == null) {
            throw new RuntimeException("未配置签约员，请联系管理员");
        }
        roleUsers.put(SIGNER_ROLE, signer);

        return roleUsers;
    }

    /**
     * 完成任务
     */
    private void completeTask(Long elderlyId, String assignee, String taskKey) {
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(elderlyId.toString())
                .taskAssignee(assignee)
                .taskDefinitionKey(taskKey)
                .singleResult();
        if (task == null) {
            throw new RuntimeException("未查询到流程任务: " + taskKey);
        }
        taskService.complete(task.getId());
        logger.debug("完成任务: {}", taskKey);
    }

    /**
     * 保存审批记录
     */
    private void saveApprovalRecord(Long elderlyId, SysUser currentUser, String currentStep,
                                    String nextStep, SysUser nextApprover, Long stepNo, Long auditStatus) {
        ElderlySzh elderly = elderlyMapper.selectElderlyById(elderlyId);
        String title = elderly.getName() + "入住申请";

        AccraditationRecord record = new AccraditationRecord();
        record.setType(ADMISSION_TYPE);
        record.setBussniessId(elderlyId);
        record.setApproverId(currentUser.getUserId());
        record.setApproverName(currentUser.getNickName());
        record.setApproverNameRole(getRoleNameByStep(stepNo));
        record.setCurrentStep(currentStep);
        record.setNextStep(nextStep);
        if (nextApprover != null) {
            record.setNextApproverId(nextApprover.getUserId());
            record.setNextApprover(nextApprover.getNickName());
            record.setNextApproverRole(getRoleNameByStep(stepNo + 1));
        }
        record.setAuditStatus(auditStatus);
        record.setStepNo(stepNo);
        record.setCreateTime(DateUtils.getNowDate());
        record.setCreateBy(currentUser.getUserId().toString());
        record.setFinishTime(DateUtils.getNowDate());
        record.setExtraField1(title);
        record.setHandleType(1L);

        accraditationRecordMapper.insertAccraditationRecordSZH(record);
        logger.debug("保存审批记录: {}", currentStep);
    }

    /**
     * 根据步骤获取角色名称
     */
    private String getRoleNameByStep(Long stepNo) {
        switch (stepNo.intValue()) {
            case 0: return "接待员";
            case 1: return "评估员";
            case 2: return "审批员";
            case 3: return "配置员";
            case 4: return "签约员";
            default: return "未知";
        }
    }

    /**
     * 创建待办任务
     */
    private void createPendingTask(Long elderlyId, SysUser assignee, SysUser applicant, Long stepNo) {
        ElderlySzh elderly = elderlyMapper.selectElderlyById(elderlyId);
        String title = elderly.getName() + "入住申请";

        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(elderlyId.toString())
                .taskAssignee(assignee.getUserId().toString())
                .taskDefinitionKey(getTaskKeyByStep(stepNo))
                .singleResult();

        if (task == null) {
            throw new RuntimeException("未查询到流程任务");
        }

        PendingTasks pendingTask = new PendingTasks();
        pendingTask.setBussniessId(elderlyId);
        pendingTask.setTaskId(task.getId());
        pendingTask.setTitle(title);
        pendingTask.setType(ADMISSION_TYPE);
        pendingTask.setAssignee(assignee.getNickName());
        pendingTask.setAssigneeId(assignee.getUserId());
        pendingTask.setStatus(PENDING_STATUS);
        pendingTask.setApplicationTime(DateUtils.getNowDate());
        pendingTask.setApplicat(applicant.getNickName());
        pendingTask.setApplicatId(applicant.getUserId());
        pendingTask.setIsHandle(0L);
        pendingTask.setStepNo(stepNo);
        pendingTask.setCreateTime(DateUtils.getNowDate());
        pendingTask.setExtraField1(title);

        pendingTasksMapper.insertPendingTasksSZH(pendingTask);
        logger.debug("创建待办任务: {}", title);
    }

    /**
     * 根据步骤获取任务键
     */
    private String getTaskKeyByStep(Long stepNo) {
        switch (stepNo.intValue()) {
            case 1: return ASSESS_TASK_KEY;
            case 2: return APPROVE_TASK_KEY;
            case 3: return CONFIG_TASK_KEY;
            default: return "";
        }
    }

    /**
     * 完成入住评估步骤
     */
    public int completeAssessmentStep(Long elderlyId, Map<String, Object> assessmentData) {
        logger.info("开始处理入住评估步骤，老人ID: {}", elderlyId);

        try {
            // 获取当前用户信息
            SysUser currentUser = getCurrentUser();

            // 保存评估数据
            saveAssessmentData(elderlyId, assessmentData, currentUser);

            // 完成评估任务
            completeTask(elderlyId, currentUser.getUserId().toString(), ASSESS_TASK_KEY);

            // 更新待办任务状态
            updatePendingTaskStatus(elderlyId, currentUser.getUserId().toString(), ASSESS_TASK_KEY);

            // 获取下一个审批人（审批员）
            SysUser approver = sysUserService.selectUserByRoleId(APPROVER_ROLE);

            // 保存评估员审批记录
            saveApprovalRecord(elderlyId, currentUser, "入住评估", "入住审批",
                    approver, 1L, APPROVED_STATUS);

            // 创建审批员待办任务
            createPendingTask(elderlyId, approver, currentUser, 2L);

            logger.info("入住评估步骤完成，老人ID: {}", elderlyId);
            return 1;

        } catch (Exception e) {
            logger.error("完成入住评估步骤失败，老人ID: {}", elderlyId, e);
            throw new RuntimeException("完成入住评估步骤失败: " + e.getMessage());
        }
    }

    /**
     * 保存评估数据
     */
    private void saveAssessmentData(Long elderlyId, Map<String, Object> assessmentData, SysUser currentUser) {
        // 保存健康评估数据
        Map<String, Object> healthData = (Map<String, Object>) assessmentData.get("healthAssessment");
        if (healthData != null) {
        HealthAssessment healthAssessment = new HealthAssessment();
        healthAssessment.setElderlyId(elderlyId);
        healthAssessment.setDiseaseDiagnosis(JSON.toJSONString(healthData.get("diseaseDiagnosis")));
        healthAssessment.setMedicationInfo(JSON.toJSONString(healthData.get("medicationInfo")));
        healthAssessment.setRiskFactors(JSON.toJSONString(healthData.get("riskFactors")));
        healthAssessment.setWoundCondition(JSON.toJSONString(healthData.get("woundCondition")));
        healthAssessment.setSpecialMedicalCare(JSON.toJSONString(healthData.get("specialMedicalCare")));
        healthAssessment.setSelfCareAbility(JSON.toJSONString(healthData.get("selfCareAbility")));
        healthAssessment.setDementiaPrecursors(JSON.toJSONString(healthData.get("dementiaPrecursors")));
        healthAssessment.setOtherConditions((String) healthData.get("otherConditions"));
        healthAssessment.setCreateTime(DateUtils.getNowDate());
            healthAssessment.setCreateBy(currentUser.getUserId().toString());
        healthAssessmentMapper.insertHealthAssessment(healthAssessment);
            logger.debug("健康评估数据保存成功");
        }

        // 保存能力评估数据
        Map<String, Object> abilityData = (Map<String, Object>) assessmentData.get("abilityAssessment");
        if (abilityData != null) {
        AbilityAssessment abilityAssessment = new AbilityAssessment();
        abilityAssessment.setElderlyId(elderlyId);
        abilityAssessment.setSelfCareAbility(JSON.toJSONString(abilityData.get("selfCareAbility")));
        abilityAssessment.setMentalStatus(JSON.toJSONString(abilityData.get("mentalStatus")));
        abilityAssessment.setPerceptionSocialParticipation(JSON.toJSONString(abilityData.get("perceptionSocial")));
        abilityAssessment.setCreateTime(DateUtils.getNowDate());
            abilityAssessment.setCreateBy(currentUser.getUserId().toString());
        abilityAssessmentMapper.insertAbilityAssessment(abilityAssessment);
            logger.debug("能力评估数据保存成功");
        }
        
        // 保存评估报告数据
        Map<String, Object> reportData = (Map<String, Object>) assessmentData.get("assessmentReport");
        if (reportData != null) {
            saveAssessmentReport(elderlyId, reportData, currentUser);
        }
    }
    
    /**
     * 保存评估报告
     */
    private void saveAssessmentReport(Long elderlyId, Map<String, Object> reportData, SysUser currentUser) {
        AssessmentReport report = new AssessmentReport();
        report.setElderlyId(elderlyId);
//        report.setSelfCareScore(parseInteger(reportData.get("selfCareScore")));
//        report.setMentalStatusScore(parseInteger(reportData.get("mentalStatusScore")));
//        report.setPerceptionSocialScore(parseInteger(reportData.get("perceptionSocialScore")));
//        report.setEstimatedTotalScore(parseInteger(reportData.get("estimatedTotalScore")));
//        report.setPreliminaryAbilityLevel((String) reportData.get("preliminaryAbilityLevel"));
//        report.setChangeBasis(JSON.toJSONString(reportData.get("changeBasis")));
//        report.setOtherBasis((String) reportData.get("otherBasis"));
//        report.setFinalLevel((String) reportData.get("finalLevel"));
//        report.setAssessmentDate(parseDate(reportData.get("assessmentDate")));
//        report.setCreateTime(DateUtils.getNowDate());
//        report.setCreateBy(currentUser.getUserId().toString());
        
        assessmentReportMapper.insertAssessmentReport(report);
        logger.debug("评估报告保存成功");
    }
    
    /**
     * 安全解析Integer类型
     */
    private Integer parseInteger(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Integer) return (Integer) obj;
        if (obj instanceof Long) return ((Long) obj).intValue();
        if (obj instanceof String) {
            try {
                return Integer.valueOf((String) obj);
            } catch (NumberFormatException e) {
                logger.warn("整数解析失败: {}", obj);
                return null;
            }
        }
        return null;
    }

    /**
     * 更新待办任务状态
     */
    private void updatePendingTaskStatus(Long elderlyId, String assignee, String taskKey) {
        Task task = taskService.createTaskQuery()
                .processInstanceBusinessKey(elderlyId.toString())
                .taskAssignee(assignee)
                .taskDefinitionKey(taskKey)
                .singleResult();

        if (task != null) {
            PendingTasks updateTask = new PendingTasks();
            updateTask.setTaskId(task.getId());
            updateTask.setIsHandle(1L); // 设置为已处理
            updateTask.setFinishTime(DateUtils.getNowDate());
            updateTask.setUpdateTime(DateUtils.getNowDate());
            updateTask.setUpdateBy(assignee);
            pendingTasksMapper.updatePendingTasks(updateTask);
            logger.debug("待办任务状态更新成功");
        }
    }

    /**
     * 完成入住审批步骤
     */
    public int completeApprovalStep(Long elderlyId, String action, String comments) {
        logger.info("开始处理入住审批步骤，老人ID: {}, 审批结果: {}", elderlyId, action);
        
        try {
            // 获取当前用户信息
            SysUser currentUser = getCurrentUser();
            
            // 验证审批结果
            validateApprovalAction(action);
            
            // 完成审批任务
            completeApprovalTask(elderlyId, currentUser.getUserId().toString(), action, comments);
            
            // 更新待办任务状态
            updatePendingTaskStatus(elderlyId, currentUser.getUserId().toString(), APPROVE_TASK_KEY);
            
            // 处理审批结果
            processApprovalResult(elderlyId, action, comments, currentUser);
            
            logger.info("入住审批步骤完成，老人ID: {}, 审批结果: {}", elderlyId, action);
            return 1;
            
        } catch (Exception e) {
            logger.error("完成入住审批步骤失败，老人ID: {}", elderlyId, e);
            throw new RuntimeException("完成入住审批步骤失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成入住配置步骤
     */
    public int completeConfigurationStep(Long elderlyId, Map<String, Object> configData) {
        logger.info("开始处理入住配置步骤，老人ID: {}", elderlyId);
        
        try {
            // 获取当前用户信息
            SysUser currentUser = getCurrentUser();
            
            // 保存入住配置数据
            saveAdmissionConfiguration(elderlyId, configData, currentUser);
            
            // 完成配置任务
            completeTask(elderlyId, currentUser.getUserId().toString(), CONFIG_TASK_KEY);
            
            // 更新待办任务状态
            updatePendingTaskStatus(elderlyId, currentUser.getUserId().toString(), CONFIG_TASK_KEY);
            
            // 获取下一个审批人（签约员）
            SysUser signer = sysUserService.selectUserByRoleId(SIGNER_ROLE);
            
            // 保存配置员审批记录
            saveApprovalRecord(elderlyId, currentUser, "入住配置", "签约办理", 
                              signer, 3L, APPROVED_STATUS);
            
            // 创建签约员待办任务
            createPendingTask(elderlyId, signer, currentUser, 4L);
            
            logger.info("入住配置步骤完成，老人ID: {}", elderlyId);
            return 1;
            
        } catch (Exception e) {
            logger.error("完成入住配置步骤失败，老人ID: {}", elderlyId, e);
            throw new RuntimeException("完成入住配置步骤失败: " + e.getMessage());
        }
    }
    
    /**
     * 保存入住配置数据
     */
    private void saveAdmissionConfiguration(Long elderlyId, Map<String, Object> configData, SysUser currentUser) {
        // 保存入住配置
        Map<String, Object> admissionConfig = (Map<String, Object>) configData.get("admissionConfig");
        if (admissionConfig != null) {
            // 这里需要根据实际的数据库表结构来保存入住配置数据
            logger.debug("保存入住配置数据: {}", admissionConfig);
        }
        
        // 保存费用配置
        Map<String, Object> feeConfig = (Map<String, Object>) configData.get("feeConfig");
        if (feeConfig != null) {
            // 这里需要根据实际的数据库表结构来保存费用配置数据
            logger.debug("保存费用配置数据: {}", feeConfig);
        }
    }
    
    /**
     * 完成签约办理步骤
     */
    public int completeContractStep(Long elderlyId, Map<String, Object> contractData) {
        logger.info("开始处理签约办理步骤，老人ID: {}", elderlyId);
        
        try {
            // 获取当前用户信息
            SysUser currentUser = getCurrentUser();
            
            // 保存合同信息
            saveContractInfo(elderlyId, contractData, currentUser);
            
            // 更新老人状态为已签约
            updateElderlyStatus(elderlyId, 3L); // 3-已签约
            
            // 保存签约员审批记录
            saveApprovalRecord(elderlyId, currentUser, "签约办理", "流程完成", 
                              null, 4L, APPROVED_STATUS);
            
            logger.info("签约办理步骤完成，老人ID: {}", elderlyId);
            return 1;
            
        } catch (Exception e) {
            logger.error("完成签约办理步骤失败，老人ID: {}", elderlyId, e);
            throw new RuntimeException("完成签约办理步骤失败: " + e.getMessage());
        }
    }
    
    /**
     * 保存合同信息
     */
    private void saveContractInfo(Long elderlyId, Map<String, Object> contractData, SysUser currentUser) {
        Map<String, Object> contractInfo = (Map<String, Object>) contractData.get("contractInfo");
        if (contractInfo != null) {
            // 这里需要根据实际的数据库表结构来保存合同信息
            logger.debug("保存合同信息: {}", contractInfo);
        }
    }
    
    /**
     * 更新老人状态
     */
    private void updateElderlyStatus(Long elderlyId, Long status) {
        ElderlySzh elderly = elderlyMapper.selectElderlyById(elderlyId);
        if (elderly != null) {
            elderly.setIsDeleted(status);
            elderlyMapper.updateElderlySzh(elderly);
            logger.debug("老人状态更新成功，ID: {}, 状态: {}", elderlyId, status);
        }
    }

    /**
     * 验证审批结果
     */
    private void validateApprovalAction(String action) {
        if (!"APPROVE".equals(action) && !"REJECT".equals(action)) {
            throw new IllegalArgumentException("无效的审批结果: " + action);
        }
    }

    /**
     * 完成审批任务
     */
    private void completeApprovalTask(Long elderlyId, String assignee, String action, String comments) {
        Task approveTask = taskService.createTaskQuery()
                .processInstanceBusinessKey(elderlyId.toString())
                .taskAssignee(assignee)
                .taskDefinitionKey(APPROVE_TASK_KEY)
                .singleResult();
        if (approveTask == null) {
            throw new RuntimeException("未找到当前用户的审批任务");
        }

        // 设置审批结果变量
        Map<String, Object> taskVars = new HashMap<>();
        taskVars.put("action", action);
        taskVars.put("comments", comments);
        taskService.complete(approveTask.getId(), taskVars);
        logger.debug("审批任务完成");
    }

    /**
     * 处理审批结果
     */
    private void processApprovalResult(Long elderlyId, String action, String comments, SysUser currentUser) {
        ElderlySzh elderly = elderlyMapper.selectElderlyById(elderlyId);
        String title = elderly.getName() + "入住申请";

        Long auditStatus = "APPROVE".equals(action) ? APPROVED_STATUS : REJECTED_STATUS;

        if ("APPROVE".equals(action)) {
            // 审批通过，创建配置员待办任务
            SysUser configurator = sysUserService.selectUserByRoleId(CONFIGURATOR_ROLE);
            saveApprovalRecord(elderlyId, currentUser, "入住审批", "入住配置",
                    configurator, 2L, auditStatus, comments);
            createPendingTask(elderlyId, configurator, currentUser, 3L);
        } else {
            // 审批拒绝，流程结束
            saveApprovalRecord(elderlyId, currentUser, "入住审批", "流程结束",
                    null, 2L, auditStatus, comments);
            
            // 更新老人状态为审批拒绝
            elderly.setIsDeleted(Long.valueOf("2")); // 审批拒绝状态
            elderlyMapper.updateElderlySzh(elderly);
            logger.info("审批拒绝，流程结束，老人ID: {}", elderlyId);
        }
    }

    /**
     * 保存审批记录（重载方法，支持意见字段）
     */
    private void saveApprovalRecord(Long elderlyId, SysUser currentUser, String currentStep,
                                    String nextStep, SysUser nextApprover, Long stepNo,
                                    Long auditStatus, String opinion) {
        ElderlySzh elderly = elderlyMapper.selectElderlyById(elderlyId);
        String title = elderly.getName() + "入住申请";

        AccraditationRecord record = new AccraditationRecord();
        record.setType(ADMISSION_TYPE);
        record.setBussniessId(elderlyId);
        record.setApproverId(currentUser.getUserId());
        record.setApproverName(currentUser.getNickName());
        record.setApproverNameRole(getRoleNameByStep(stepNo));
        record.setCurrentStep(currentStep);
        record.setNextStep(nextStep);
        record.setOpinion(opinion);
        record.setAuditStatus(auditStatus);
        record.setStepNo(stepNo);
        record.setCreateTime(DateUtils.getNowDate());
        record.setCreateBy(currentUser.getUserId().toString());
        record.setFinishTime(DateUtils.getNowDate());
        record.setExtraField1(title);
        record.setHandleType(1L);

        if (nextApprover != null) {
            record.setNextApproverId(nextApprover.getUserId());
            record.setNextApprover(nextApprover.getNickName());
            record.setNextApproverRole(getRoleNameByStep(stepNo + 1));
        }

        accraditationRecordMapper.insertAccraditationRecordSZH(record);
        logger.debug("保存审批记录: {}", currentStep);
    }

    /**
     * 获取用户的待办任务
     */
    public List<PendingTasks> getUserPendingTasks() {
        try {
            SysUser currentUser = getCurrentUser();
        PendingTasks pendingTasks = new PendingTasks();
        pendingTasks.setStatus(0L);
        pendingTasks.setAssigneeId(currentUser.getUserId());
            List<PendingTasks> tasks = pendingTasksMapper.selectPendingTasksList(pendingTasks);
            logger.debug("获取用户待办任务成功，数量: {}", tasks.size());
            return tasks;
        } catch (Exception e) {
            logger.error("获取用户待办任务失败", e);
            throw new RuntimeException("获取用户待办任务失败: " + e.getMessage());
        }
    }

    /**
     * 根据任务ID获取跳转信息
     */
    public Map<String, Object> getTaskRedirectInfo(String taskId) {
        try {
        PendingTasks task = pendingTasksMapper.selectPendingTasksById(Long.valueOf(taskId));
        if (task == null) {
            throw new RuntimeException("待办任务不存在");
        }

        // 根据步骤号确定前端步骤
        Integer frontendStep = getFrontendStepByStepNo(Math.toIntExact(task.getStepNo()));

        Map<String, Object> result = new HashMap<>();
        result.put("elderlyId", task.getBussniessId());
        result.put("step", frontendStep);
        result.put("taskId", taskId);
        result.put("title", task.getTitle());
        result.put("stepNo", task.getStepNo());

            logger.debug("获取任务跳转信息成功，任务ID: {}, 步骤: {}", taskId, frontendStep);
        return result;
        } catch (Exception e) {
            logger.error("获取任务跳转信息失败，任务ID: {}", taskId, e);
            throw new RuntimeException("获取任务跳转信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据步骤号获取前端步骤
     */
    private Integer getFrontendStepByStepNo(Integer stepNo) {
        switch (stepNo) {
            case 0: return 1; // 申请入住
            case 1: return 2; // 入住评估
            case 2: return 3; // 入住审批
            case 3: return 4; // 入住配置
            case 4: return 5; // 签约办理
            default: return 1;
        }
    }
}